package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"strconv"
	"time"

	"golang/sorter/src/algorithm/bubble_sort"
	"golang/sorter/src/algorithm/quick_sort"
)

var iarg = flag.String("i", "./conf/input", "input file")
var oarg = flag.String("o", "./conf/output", "output file")
var aarg = flag.String("a", "algorithm", "algorithm")

func read(filename *string) (vals []int, err error) {
	file, err := os.Open(*filename)
	if err != nil {
		fmt.Println("open file", *filename, "failed")
		return
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	vals = make([]int, 0, 10)

	for {
		line, prefix, err := reader.ReadLine()
		if err != nil {
			if err != io.EOF {
				err = nil
			}
			break
		}

		if prefix {
			fmt.Println("unexpected")
			return nil, err
		}

		val, err := strconv.Atoi(string(line))
		if err != nil {
			return nil, err
		}

		vals = append(vals, val)
	}

	return vals, nil
}

func write(filename *string, vals []int) (err error) {
	file, err := os.Create(*filename)
	if err != nil {
		return err
	}
	defer file.Close()

	for _, val := range vals {
		file.WriteString(strconv.Itoa(val) + "\n")
	}

	return nil
}

func main() {
	flag.Parse()

	fmt.Println(*iarg, *oarg, *aarg)

	vals, err := read(iarg)
	if err == nil {
		begin := time.Now()
		switch *aarg {
		case "quick_sort":
			quick_sort.QuickSort(vals)
		case "bubble_sort":
			bubble_sort.BubbleSort(vals)
		default:
			quick_sort.QuickSort(vals)
		}
		if write(oarg, vals) != nil {
			fmt.Println("write to file failed")
		}
		end := time.Now()
		fmt.Println("sorting costs:", end.Sub(begin))
	}

}
